import { headers } from 'next/headers';

// get current page url
export function getLocationUrl(url?: string) {
  const headersObj = headers();
  if (url) {
    try {
      const returnUrlObj = new URL(url);
      const headerHost = headersObj.get('host');
      if (returnUrlObj.hostname == 'localhost' && headerHost) {
        const headerUrlObj = new URL(`${returnUrlObj.protocol}//${headerHost}`);
        returnUrlObj.host = headerUrlObj.host;
        returnUrlObj.port = headerUrlObj.port;
        return returnUrlObj.toString();
      }
      return url;
    } catch (error) {
      return url;
    }
  }
  return headersObj.get('referer') || headersObj.get('x-original-uri') || '';
}

export function getHeader(name: string) {
  const headersObj = headers();
  return headersObj.get(name) || '';
}
